<template>
  <div class="convert-container">
    <div class="page-header">
      <el-page-header @back="goBack" title="返回" content="图片格式转换" />
    </div>

    <div class="main-content">
      <div class="upload-section">
        <h2>批量图片格式转换</h2>
        <p class="description">
          将您的图片批量转换为其他格式，支持PNG、JPG、GIF、WEBP等格式互转。
        </p>

        <div class="format-selector">
          <span class="format-label">目标格式：</span>
          <el-radio-group v-model="targetFormat" size="large">
            <el-radio-button label="png">PNG</el-radio-button>
            <el-radio-button label="jpg">JPG</el-radio-button>
            <el-radio-button label="webp">WEBP</el-radio-button>
            <el-radio-button label="gif">GIF</el-radio-button>
          </el-radio-group>
        </div>

        <el-upload
          class="upload-area"
          drag
          multiple
          list-type="picture-card"
          :auto-upload="false"
          :before-upload="handleBeforeUpload"
          :on-remove="handleFileRemove"
          v-model:file-list="fileList"
          :limit="10"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持PNG、JPG、GIF、WEBP格式，每个文件不超过30MB，最多10个文件
            </div>
          </template>
        </el-upload>

        <div class="action-buttons">
          <el-button 
            type="primary" 
            :disabled="fileList.length === 0" 
            :loading="uploading" 
            @click="startConvert"
          >
            开始转换
          </el-button>
          <el-button @click="clearFiles" :disabled="fileList.length === 0 || uploading">
            清空文件
          </el-button>
        </div>
      </div>

      <div class="results-section" v-if="results.length > 0 || (uploading && previousResults)">
        <div v-if="uploading" class="loading-container">
          <el-skeleton :rows="3" animated />
          <div class="loading-icon-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <p>正在转换图片，请稍候...</p>
          </div>
        </div>
        
        <div v-else>
          <div class="results-summary">
            <h3>转换结果</h3>
            <p>
              成功转换 {{ successCount }} 张图片，
              失败 {{ failureCount }} 张图片
            </p>
          </div>

          <el-table :data="results" style="width: 100%" border>
            <el-table-column prop="original_filename" label="原始文件名" min-width="180" />
            <el-table-column prop="converted_filename" label="转换后文件名" min-width="180" />
            <el-table-column prop="original_format" label="原始格式" width="100" />
            <el-table-column prop="target_format" label="目标格式" width="100" />
            <el-table-column label="原始大小" width="120">
              <template #default="scope">
                {{ formatFileSize(scope.row.original_size) }}
              </template>
            </el-table-column>
            <el-table-column label="转换后大小" width="120">
              <template #default="scope">
                {{ formatFileSize(scope.row.converted_size) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button 
                  v-if="!scope.row.error" 
                  type="primary" 
                  link 
                  @click="downloadFile(scope.row)"
                >
                  下载
                </el-button>
                <el-tooltip 
                  v-else 
                  effect="dark" 
                  :content="scope.row.error" 
                  placement="top"
                >
                  <el-button type="danger" link>失败</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <div class="download-all" v-if="successCount > 0">
            <el-button type="success" @click="downloadAllFiles">
              下载全部转换成功的图片
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { UploadFilled, Loading } from '@element-plus/icons-vue'

export default {
  name: 'ConvertView',
  components: {
    UploadFilled,
    Loading
  },
  setup() {
    const router = useRouter()
    const fileList = ref([])
    const results = ref([])
    const uploading = ref(false)
    const previousResults = ref(false)
    const targetFormat = ref('png')

    const successCount = computed(() => {
      return results.value.filter(item => !item.error).length
    })

    const failureCount = computed(() => {
      return results.value.filter(item => item.error).length
    })

    const goBack = () => {
      router.push('/')
    }

    const handleBeforeUpload = (file) => {
      // 检查文件类型
      const extension = file.name.split('.').pop().toLowerCase()
      const allowedTypes = ['png', 'jpg', 'jpeg', 'gif', 'webp']
      
      if (!allowedTypes.includes(extension)) {
        ElMessage.error(`不支持的文件类型: ${extension}`)
        return false
      }
      
      // 检查文件大小
      const maxSize = 30 * 1024 * 1024 // 30MB
      if (file.size > maxSize) {
        ElMessage.error(`文件大小超过限制: ${file.name}`)
        return false
      }
      
      return true
    }

    const handleFileRemove = (file) => {
      const index = fileList.value.indexOf(file)
      if (index !== -1) {
        fileList.value.splice(index, 1)
      }
    }

    const clearFiles = () => {
      fileList.value = []
    }

    const startConvert = async () => {
      if (fileList.value.length === 0) {
        ElMessage.warning('请先选择要转换的图片')
        return
      }

      uploading.value = true
      if (results.value.length > 0) {
        previousResults.value = true
      }

      const formData = new FormData()
      fileList.value.forEach(file => {
        formData.append('files[]', file.raw)
      })
      formData.append('format', targetFormat.value)

      try {
        const response = await fetch('/api/convert', {
          method: 'POST',
          body: formData
        })

        if (!response.ok) {
          const errorData = await response.json()
          throw new Error(errorData.error || '转换失败')
        }

        const data = await response.json()
        results.value = data.results
        
        if (successCount.value > 0) {
          ElMessage.success(`成功转换 ${successCount.value} 张图片`)
        }
        
        if (failureCount.value > 0) {
          ElMessage.warning(`${failureCount.value} 张图片转换失败`)
        }
      } catch (error) {
        ElMessage.error(`转换出错: ${error.message}`)
        console.error('转换出错:', error)
      } finally {
        uploading.value = false
        previousResults.value = false
      }
    }

    const downloadFile = (file) => {
      if (file.url) {
        const link = document.createElement('a')
        link.href = file.url
        link.download = file.converted_filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    }

    const downloadAllFiles = () => {
      const successFiles = results.value.filter(item => !item.error)
      if (successFiles.length === 0) return
      
      successFiles.forEach(file => {
        downloadFile(file)
      })
    }

    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else {
        return (size / (1024 * 1024)).toFixed(2) + ' MB'
      }
    }

    return {
      fileList,
      results,
      uploading,
      previousResults,
      targetFormat,
      successCount,
      failureCount,
      goBack,
      handleBeforeUpload,
      handleFileRemove,
      clearFiles,
      startConvert,
      downloadFile,
      downloadAllFiles,
      formatFileSize
    }
  }
}
</script>

<style scoped>
.convert-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.upload-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.description {
  color: #606266;
  margin-bottom: 20px;
}

.format-selector {
  margin-bottom: 20px;
}

.format-label {
  margin-right: 10px;
  font-weight: bold;
}

.upload-area {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.results-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.results-summary {
  margin-bottom: 20px;
}

.download-all {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.loading-icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.loading-icon {
  font-size: 30px;
  color: #409eff;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
<style>
.convert-container .upload-area .el-upload {
    --el-upload-dragger-padding-horizontal: 10px;
}
</style>